package com.macro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.macro.enums.AppHttpCodeEnum;
import com.macro.mapper.*;
import com.macro.pojos.dto.*;
import com.macro.pojos.pojo.*;
import com.macro.service.GoodsService;
import com.macro.utils.FastDFSClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsSkuStockMapper goodsSkuStockMapper;
    @Autowired
    private GoodsMemberPriceMapper goodsMemberPriceMapper;
    @Autowired
    private GoodsLadderMapper goodsLadderMapper;
    @Autowired
    private GoodsFullReductionMapper goodsFullReductionMapper;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;
    @Autowired
    private GoodsAttributeCategoryMapper goodsAttributeCategoryMapper;
    @Autowired
    private GoodsAttributeValueMapper goodsAttributeValueMapper;
    @Autowired
    private UiSubjectMapper uiSubjectMapper;
    @Autowired
    private UiPrefrenceMapper uiPrefrenceMapper;

    @Override
    public ResponseResult queryGoods(UiGoodsDto uiGoodsDto) {
        uiGoodsDto.setNum((uiGoodsDto.getPage()-1)*uiGoodsDto.getSize());
        List<UiGoods> goodsList = goodsMapper.queryGoods(uiGoodsDto);
        if (CollectionUtils.isEmpty(goodsList)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        for (UiGoods uiGoods : goodsList) {
            uiGoods.setGoodsPicture(fileServerUrl + uiGoods.getGoodsPicture());
        }
        return ResponseResult.okResult(goodsList);
    }

    @Override
    public ResponseResult batchGoods(BatchChangeDto batchChangeDto) {
        if (batchChangeDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        UiGoods uiGoods = new UiGoods();
        for (Integer id : batchChangeDto.getIds()) {
            uiGoods = goodsMapper.selectById(id);
            switch (batchChangeDto.getBatchId()) {
                case 0://上架
                    uiGoods.setPublishStatus(1);
                    break;
                case 1://下架
                    uiGoods.setPublishStatus(0);
                    break;
                case 2://推荐
                    uiGoods.setRecommandStatus(1);
                    break;
                case 3://取推
                    uiGoods.setRecommandStatus(0);
                    break;
                case 4://新品
                    uiGoods.setNewStatus(1);
                    break;
                case 5://旧品
                    uiGoods.setNewStatus(0);
                    break;
                case 6://转移
                    uiGoods.setCategoryId(batchChangeDto.getCategoryId());
                    break;
                case 7://回收
                    uiGoods.setIsDeleted(1);
                    break;
                default:
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            int result = goodsMapper.updateById(uiGoods);
            if (result == 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult labelChange(LabelChangeDto labelChangeDto) {
        UiGoods uiGoods = new UiGoods();
        BeanUtils.copyProperties(labelChangeDto,uiGoods);
        int result = goodsMapper.updateById(uiGoods);
        if (result != 0)
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
    }
    
    /**
     * 添加商品信息
     *
     * @param uiGoodsAddDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//本地事务
    public ResponseResult addGoods(UiGoodsAddDto uiGoodsAddDto) {
        //判断参数
        if (uiGoodsAddDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //新建对象
        UiGoods uiGoods = new UiGoods();
        //复制属性
        BeanUtils.copyProperties(uiGoodsAddDto, uiGoods);
        uiGoods.setCreatedTime(new Date());
        uiGoods.setUpdatedTime(new Date());
        //1.特惠促销 2.会员价格 3.阶梯价格 4.满减价格 0.无优惠
        switch (uiGoodsAddDto.getPromotionType()) {
            case 1:
                uiGoods.setPromotionStartTime(new Date());
                uiGoods.setPromotionEndTime(new Date());
                uiGoods.setPromotionPrice(uiGoodsAddDto.getPromotionPrice());
                break;
            case 2:
                BigDecimal[] memberPrices = {uiGoodsAddDto.getMemberPrice1(), uiGoodsAddDto.getMemberPrice2(), uiGoodsAddDto.getMemberPrice2()};
                memberPrice(uiGoodsAddDto.getGoodsSn(), memberPrices);
                break;
            case 3:
                ladderPrice(uiGoodsAddDto.getGoodsSn(), uiGoodsAddDto.getLadderDtos());
                break;
            case 4:
                fullReduction(uiGoodsAddDto.getGoodsSn(), uiGoodsAddDto.getFullReductionDtoList());
                break;
            default:
                break;
        }

        //添加参数
        UiGoodsAttributeValue uiGoodsAttributeValue = new UiGoodsAttributeValue();
        uiGoodsAttributeValue.setCreatedTime(new Date());
        uiGoodsAttributeValue.setUpdatedTime(new Date());
        uiGoodsAttributeValue.setGoodsSn(uiGoodsAddDto.getGoodsSn());
        uiGoodsAttributeValue.setGoodsAttributeId(uiGoodsAddDto.getGoodsAttributeId());
        uiGoodsAttributeValue.setValue(uiGoodsAddDto.getValue());
        goodsAttributeValueMapper.insert(uiGoodsAttributeValue);

        //添加图片
        uiGoods.setAlumPictures(uiGoodsAddDto.getAlumPictures().toString());
        //添加文本
        uiGoods.setDetailMobileHtml(uiGoodsAddDto.getDetailMobileHtml());
        uiGoods.setDetailPcHtml(uiGoodsAddDto.getDetailPcHtml());
        //最终添加
        int goodsResult = goodsMapper.insert(uiGoods);
        if (goodsResult == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
        }

        //添加商品规格
        List<UiGoodsSkuStock> skuStocks = uiGoodsAddDto.getSkuStocks();
        for (UiGoodsSkuStock skuStock : skuStocks) {
            UiGoodsSkuStock uiGoodsSkuStock = new UiGoodsSkuStock();
            BeanUtils.copyProperties(skuStock, uiGoodsSkuStock);
            Integer skuResult = addSkuStock(uiGoodsSkuStock);
            if (skuResult == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }

        //专题
        for (int subId : uiGoodsAddDto.getSubIds()) {
            int suI = uiSubjectMapper.addSubject(subId, uiGoods.getGoodsId());
            if (suI == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }
        //优选
        for (int preId : uiGoodsAddDto.getPreIds()) {
            int prI = uiPrefrenceMapper.addPrefrence(preId, uiGoods.getGoodsId());
            if (prI == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 修改商品信息
     *
     * @param uiGoodsAddDto
     * @return
     */
    @Override
    public ResponseResult updateGoods(UiGoodsAddDto uiGoodsAddDto) {

        //判断参数
        if (uiGoodsAddDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //新建对象
        UiGoods uiGoods = new UiGoods();
        //复制属性
        BeanUtils.copyProperties(uiGoodsAddDto, uiGoods);
        uiGoods.setCreatedTime(new Date());
        uiGoods.setUpdatedTime(new Date());
        //1.特惠促销 2.会员价格 3.阶梯价格 4.满减价格 0.无优惠
        switch (uiGoodsAddDto.getPromotionType()) {
            case 1:
                uiGoods.setPromotionStartTime(new Date());
                uiGoods.setPromotionEndTime(new Date());
                uiGoods.setPromotionPrice(uiGoodsAddDto.getPromotionPrice());
                break;
            case 2:
                BigDecimal[] memberPrices = {uiGoodsAddDto.getMemberPrice1(), uiGoodsAddDto.getMemberPrice2(), uiGoodsAddDto.getMemberPrice2()};
                memberPrice(uiGoodsAddDto.getGoodsSn(), memberPrices);
                break;
            case 3:
                ladderPrice(uiGoodsAddDto.getGoodsSn(), uiGoodsAddDto.getLadderDtos());
                break;
            case 4:
                fullReduction(uiGoodsAddDto.getGoodsSn(), uiGoodsAddDto.getFullReductionDtoList());
                break;
            default:
                break;
        }

        //添加参数
        UiGoodsAttributeValue uiGoodsAttributeValue = new UiGoodsAttributeValue();
        uiGoodsAttributeValue.setCreatedTime(new Date());
        uiGoodsAttributeValue.setUpdatedTime(new Date());
        uiGoodsAttributeValue.setGoodsSn(uiGoodsAddDto.getGoodsSn());
        uiGoodsAttributeValue.setGoodsAttributeId(uiGoodsAddDto.getGoodsAttributeId());
        uiGoodsAttributeValue.setValue(uiGoodsAddDto.getValue());
        goodsAttributeValueMapper.updateById(uiGoodsAttributeValue);

        //添加图片
        uiGoods.setAlumPictures(uiGoodsAddDto.getAlumPictures().toString());
        //添加文本
        uiGoods.setDetailMobileHtml(uiGoodsAddDto.getDetailMobileHtml());
        uiGoods.setDetailPcHtml(uiGoodsAddDto.getDetailPcHtml());
        //最终添加
        int goodsResult = goodsMapper.updateById(uiGoods);
        if (goodsResult == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
        }

        //修改商品规格
        List<UiGoodsSkuStock> skuStocks = uiGoodsAddDto.getSkuStocks();
        for (UiGoodsSkuStock skuStock : skuStocks) {
            UiGoodsSkuStock uiGoodsSkuStock = new UiGoodsSkuStock();
            BeanUtils.copyProperties(skuStock, uiGoodsSkuStock);
            Integer skuResult = updateSkuStock(uiGoodsSkuStock);
            if (skuResult == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }

        //专题
        for (int subId : uiGoodsAddDto.getSubIds()) {
            int suI = uiSubjectMapper.addSubject(subId, uiGoods.getGoodsId());
            if (suI == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }
        //优选
        for (int preId : uiGoodsAddDto.getPreIds()) {
            int prI = uiPrefrenceMapper.addPrefrence(preId, uiGoods.getGoodsId());
            if (prI == 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 根据id删除单个商品
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delGoodsById(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer[] skuId = goodsSkuStockMapper.queySkuId(goodsMapper.selectById(id).getGoodsSn());
        for (Integer integer : skuId) {
            int resultSku = goodsSkuStockMapper.deleteById(integer);
            if (resultSku > 0) {
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
        int resultGoods = goodsMapper.deleteById(id);
        if (resultGoods > 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        return ResponseResult.errorResult(400, "删除失败");
    }

    /**
     * 满减优惠
     *
     * @param goodsSn
     * @param fullReductionDtoList
     */
    private void fullReduction(String goodsSn, List<UiGoodsFullReductionDto> fullReductionDtoList) {
        for (UiGoodsFullReductionDto uiGoodsFullReductionDto : fullReductionDtoList) {
            UiGoodsFullReduction uiGoodsFullReduction = new UiGoodsFullReduction();
            BeanUtils.copyProperties(uiGoodsFullReductionDto, uiGoodsFullReduction);
            uiGoodsFullReduction.setGoodsSn(goodsSn);
            uiGoodsFullReduction.setCreatedTime(new Date());
            goodsFullReductionMapper.insert(uiGoodsFullReduction);
        }

    }


    /**
     * 阶梯价格
     */
    private void ladderPrice(String goodsSn, List<UiGoodsLadderDto> ladderDtos) {
        for (UiGoodsLadderDto ladderDto : ladderDtos) {
            UiGoodsLadder uiGoodsLadder = new UiGoodsLadder();
            BeanUtils.copyProperties(ladderDto, uiGoodsLadder);
            uiGoodsLadder.setGoodsSn(goodsSn);
            uiGoodsLadder.setCreatedTime(new Date());
            goodsLadderMapper.insert(uiGoodsLadder);
        }
    }


    /**
     * 促销会员表
     *
     * @param goodsSn
     */
    private void memberPrice(String goodsSn, BigDecimal[] memberPrices) {
        String[] memberName = {"黄金会员", "白金会员", "钻石会员"};
        for (int i = 0; i < memberPrices.length; i++) {
            UiGoodsMemberPrice uiGoodsMemberPrice = new UiGoodsMemberPrice();
            uiGoodsMemberPrice.setGoodsSn(goodsSn);
            uiGoodsMemberPrice.setMemberPrice(memberPrices[i]);
            uiGoodsMemberPrice.setMemberLevelName(memberName[i]);
            uiGoodsMemberPrice.setCreatedTime(new Date());
            uiGoodsMemberPrice.setMemberLevelId(i + 1);
            goodsMemberPriceMapper.insert(uiGoodsMemberPrice);
        }
    }

    /**
     * 添加商品规格信息
     *
     * @param uiGoodsSkuStock
     * @return
     */
    private Integer addSkuStock(UiGoodsSkuStock uiGoodsSkuStock) {
        return goodsSkuStockMapper.insert(uiGoodsSkuStock);

    }

    /**
     * 修改商品规格信息
     *
     * @param uiGoodsSkuStock
     * @return
     */
    private Integer updateSkuStock(UiGoodsSkuStock uiGoodsSkuStock) {
        return goodsSkuStockMapper.updateById(uiGoodsSkuStock);
    }


    /**
     * 相册上传（含主图）
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile file) throws IOException {
        if (file == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String url = fastDFSClientUtil.uploadFile(file);
        if (url == null || url.equals("")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.FAIL);
        }
        return ResponseResult.okResult(url);
    }

    /**
     * 查询商品类型
     *
     * @return
     */
    @Override
    public ResponseResult findGoodsType(UiGoodsAttributeCategory uiGoodsAttributeCategory) {
        List<UiGoodsAttributeCategory> categoryList = goodsAttributeCategoryMapper.findGoodsType(uiGoodsAttributeCategory);
        if (CollectionUtils.isEmpty(categoryList)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(categoryList);
    }

    /**
     * 查询商品类别所对应的规格和参数
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findAttributeAndParm(Integer id) {
        List<UiGoodsAttributeCategoryDto> categoryDtoList = goodsAttributeCategoryMapper.findAttributeAndParm(id);
        if (CollectionUtils.isEmpty(categoryDtoList)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(categoryDtoList);
    }

    /**
     * 查询所有专题
     *
     * @param subTitle
     * @return
     */
    @Override
    public ResponseResult findAllSubject(String subTitle) {
        LambdaQueryWrapper<UiSubject> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(UiSubject::getSubTitle, subTitle);
        List<UiSubject> uiSubjects = uiSubjectMapper.selectList(lambdaQueryWrapper);
        return ResponseResult.okResult(uiSubjects);
    }

    /**
     * 查询所有优选
     *
     * @param preferNname
     * @return
     */
    @Override
    public ResponseResult findAllPreference(String preferNname) {
        LambdaQueryWrapper<UiPrefrence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(UiPrefrence::getPreferName, preferNname);
        List<UiPrefrence> uiPrefrences = uiPrefrenceMapper.selectList(lambdaQueryWrapper);
        return ResponseResult.okResult(uiPrefrences);
    }
}
